import axios from "axios";
import querystring from "querystring";
import CONSTANT from "./constant";
import Api from "./api";

import router from "../router";
import {
    ElNotification,
    ElMessageBox,
    ElMessage
} from "element-plus";

const errorHandle = (status, info) => {
    switch (status) {
        case 400:
            console.log("语义有误");
            break;
        case 401:
            console.log("服务器认证失败");
            break;
        case 43:
            console.log("服务器拒绝访问");
            break;
        case 404:
            console.log("地址有误");
            break;
        case 500:
            console.log("服务器报出异常");
            break;
        case 502:
            console.log("服务器报无响应");
            break;
        default:
            console.log(info);
    }
};

//1. 创建axios实例
const instance = axios.create({
    baseURL: CONSTANT.BASE_URL,
    headers: {
        "Content-Type": "multipart/form-data",
    },
    timeout: 5000,
});
//2. 请求拦截器 -- 发起请求前被拦住 -- 统一设置请求头加入参数等
instance.interceptors.request.use(
    (config) => {
        // if (config.method == "post") {
        //     config.data = querystring.stringify(config.data)
        // }
        if (config.type) {
            if (config.type === CONSTANT.FORM_REQUEST_TYPE) {
                config.data = searchParams(config.data);
            }
            config.headers["Content-Type"] = config.type || CONSTANT.JSON_REQUEST_TYPE;
        }
        config.loading && loading(config.loading);
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);
let isLogin = false;
let loginItv = 0;
const toLoginPage = () => {
    if (!isLogin) {
        isLogin = true;
        clearTimeout(loginItv);
        // ElMessage({
        //     message: '当前登陆状态失效，即将进入登录页面',
        //     type: "info",
        //     duration: 2000,
        // });
        loginItv = setTimeout(() => {
            let curUrl = encodeURIComponent(location.href);
            location.replace(`/car_wash/admin/login?from_url=${curUrl}`);
        }, 2000);
    }
};

//3. 响应拦截器 -- 接口返回数据时候被拦住 -- 统一判断状态码/数据格式化
instance.interceptors.response.use(
    (response) => {
        const {
            config = {}, data = {}, status
        } = response;
        const {
            loading
        } = config;
        loading && hideLoading(true);
        return status == 200 ? Promise.resolve(data) : Promise.reject(response);
    },
    (error) => {
        loading && hideLoading(false);

        let response = error?.response ?? {};
        let status = response?.status;

        // 已经是登录页面，不用跳转
        // 1. 401: 是不是登录接口；是不是已经处于登录页面；
        let errMsg = response?.data?.detail ?? "";
        if (!errMsg) {
            errMsg = error?.message || "未知错误";
        }
        ElMessage({
            message: errMsg,
            type: "warning",
            duration: 1000,
        });
        if (status === 401 && error.config.url !== "/car_wash_api/v1/auth/token" && location.pathname !==
            "/car_wash/admin/login") {
            toLoginPage();
        }
        return Promise.reject(error);
    }
);
//设置请求参数格式
function searchParams(data) {
    if (data === "{}") return {};
    let params = new URLSearchParams();
    for (let key in data) {
        params.append(key, data[key]);
    }
    return params;
}
//cookie存数据
function saveCookie(key, value, options) {
    if (
        arguments.length > 1 &&
        (!/Object/.test(Object.prototype.toString.call(value)) || value === null || value === undefined)
    ) {
        options = options || {};
        (value === null || value === undefined) && (options.expires = -1);
        if (typeof options.expires === "number") {
            let days = options.expires,
                t = (options.expires = new Date());
            //expires以时间天为单位，接受小数
            t.setTime(t.getTime() + parseInt(days * 24 * 60 * 60 * 1000));
        }
        value = String(value);
        return (document.cookie = [
            encodeURIComponent(key),
            "=",
            options.raw ? value : encodeURIComponent(value),
            options.expires ? "; expires=" + options.expires.toUTCString() : "",
            options.path ? "; path=" + options.path : "",
        ].join(""));
    }
    options = value || {};
    let decode = options.raw ?
        function(s) {
            return s;
        } :
        decodeURIComponent;
    let pairs = document.cookie.split(";");
    for (let i = 0, len = pairs.length; i < len; i++) {
        let item = pairs[i],
            index = item ? item.indexOf("=") : -1,
            k,
            v;
        if (index !== -1) {
            k = item.substring(0, index);
            v = item.substring(index + 1, item ? item.length : 0);
            if (decode(k) === key) {
                return decode(v || "");
            }
        }
    }
    return null;
}
//登录统一loading加载提示
function loading(data) {}
//隐藏loading
function hideLoading(status) {}
//统一登录接口
function commonLogin(opt, cb) {
    const {
        data = {}
    } = opt || {};
    return new Promise((resolve) => {
        return instance
            .request({
                url: Api.LOGIN_PATH,
                method: "POST",
                data,
                loading: false,
                type: CONSTANT.FORM_DATA_REQUEST,
            })
            .then((res, status, xhr) => {
                const {
                    access_token
                } = res;
                //存储token
                saveCookie("accessToken", access_token, {
                    expires: 7,
                    path: "/"
                });
                cb && cb(true);
                resolve(res);
            }).catch(error => {
				cb && cb(false)
			});
    });
}
async function ajax(opt, success, fail) {
    const {
        url,
        method,
        contentType,
        data,
        needToken,
        loading
    } = opt || {};
    let headerObj = {
        "content-type": contentType || "application/json"
    };
    //接口需要登录态
    if (needToken) {
        let access_token = saveCookie("accessToken") || "";
        headerObj = {
            Authorization: `Bearer ${access_token}`,
            ...headerObj
        };
    }
    return instance
        .request({
            url,
            method: method || "POST",
            headers: headerObj,
            data,
            loading,
        })
        .then((res, status, xhr) => {
            const {
                code,
                data,
                message
            } = res;
            if (code !== 10000) {
                ElMessage({
                    message: message || "业务接口异常",
                    type: "warning",
                    duration: 1000,
                });
                fail && fail(res);
            } else {
                success && success(res);
            }
        });
}
export default {
    commonLogin,
    ajax,
    get(url, params) {
        return instance.get(url, params);
    },
    post(url, data) {
        return instance.post(url, data);
    },
};